<template>
  <div class="knowledge-management-container">
    
    <div class="main-content">
      <!-- 知识分类导航 -->
      <div class="navigation-sidebar">
        <KnowledgeTypeNavigation ref="typeNavigationRef" @type-selected="onTypeSelected" />
      </div>
      
      <!-- 主要内容区域 -->
      <div class="content-area">
        <div class="filter-section">
          <div class="search-box">
            <input 
              type="text" 
              placeholder="搜索知识..." 
              class="search-input" 
              v-model="searchKeyword"
              @input="onSearch"
            />
            <button 
              v-if="searchKeyword" 
              class="clear-btn" 
              @click="clearSearch"
              title="清除搜索"
            >
              ×
            </button>
          </div>
          <button class="upload-btn" @click="openUploadModal">
            <span class="btn-icon">📁</span>
            <span class="btn-text">上传文件</span>
          </button>
        </div>
    
        <div class="knowledge-table">
          <table>
            <thead>
              <tr>
                <th><input type="checkbox" /></th>
                <th>标题</th>
                <th>分类</th>
                <th>作者</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading">
                <td colspan="6" class="loading-cell">
                  <div class="loading-spinner"></div>
                  <span>正在加载知识文档...</span>
                </td>
              </tr>
              <tr v-else-if="filteredKnowledge.length === 0 && !loading" class="empty-row">
                <td colspan="6" class="empty-cell">
                  <div class="empty-content">
                    <span class="empty-icon">📚</span>
                    <h3>暂无知识文档</h3>
                    <p>还没有任何知识文档，点击"上传文件"开始添加</p>
                  </div>
                </td>
              </tr>
              <tr v-else v-for="knowledge in filteredKnowledge" :key="knowledge.kno_id" class="table-row">
                <td><input type="checkbox" /></td>
                <td>
                  <div class="title-with-watermark">
                    <span class="title-text">{{ knowledge.kno_title }}</span>
                    <span 
                      class="status-watermark" 
                      :class="getStatusClass(knowledge.kno_style)"
                    >
                      {{ getStatusText(knowledge.kno_style) }}
                    </span>
                  </div>
                </td>
                <td>{{ knowledge.kno_type }}</td>
                <td>{{ knowledge.kno_authid }}</td>
                <td>{{ formatDateTime(knowledge.kno_createtime) }}</td>
                <td>
                  <button class="btn-sm use-btn" @click="handleUse(knowledge)">预览</button>
                  <button class="btn-sm delete-btn" @click="handleDelete(knowledge)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
      </div>
    </div>

    <!-- 自定义提示框 -->
    <div v-if="showAlert" class="custom-alert-overlay" @click="handleAlertClose">
      <div class="custom-alert" @click.stop>
        <div class="alert-icon" :class="alertType">
          <span v-if="alertType === 'success'">✓</span>
          <span v-else-if="alertType === 'error'">✗</span>
          <span v-else>ℹ</span>
        </div>
        <div class="alert-content">
          <h3>{{ alertMessage }}</h3>
        </div>
        <button class="alert-btn" @click="handleAlertClose">确定</button>
      </div>
    </div>

    <!-- 自定义确认框 -->
    <div v-if="showConfirm" class="custom-confirm-overlay" @click="handleConfirmNo">
      <div class="custom-confirm" @click.stop>
        <div class="confirm-icon">❓</div>
        <div class="confirm-content">
          <h3>{{ confirmMessage }}</h3>
        </div>
        <div class="confirm-buttons">
          <button class="confirm-btn cancel" @click="handleConfirmNo">取消</button>
          <button class="confirm-btn confirm" @click="handleConfirmYes">确定</button>
        </div>
      </div>
    </div>

    <!-- 文档上传弹窗 -->
    <DocumentUploadModal 
      :show="showUploadModal"
      @close="closeUploadModal"
      @upload-success="handleUploadSuccess"
    />

    <!-- 文档预览弹窗 -->
    <DocumentPreviewModal 
      :show="showPreviewModal"
      :document="previewDocument"
      @close="closePreviewModal"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import KnowledgeTypeNavigation from '@/components/tabbar/KnowledgeManagement/KnowledgeTypeNavigation.vue'
import DocumentUploadModal from '@/components/tabbar/KnowledgeManagement/DocumentUploadModal.vue'
import DocumentPreviewModal from '@/components/tabbar/KnowledgeManagement/DocumentPreviewModal.vue'
import { getKnowledges, deleteKnowledge } from '@/api/knowledge'
import { getUser } from '@/utils/tools/auth'

// 响应式数据
const searchKeyword = ref('')
const selectedTypeId = ref(null)
const knowledgeList = ref([])
const loading = ref(false)
const selectedType = ref(null)
const typeNavigationRef = ref(null)

// 上传弹窗状态
const showUploadModal = ref(false)

// 预览弹窗状态
const showPreviewModal = ref(false)
const previewDocument = ref(null)

// 提示状态
const showAlert = ref(false)
const alertMessage = ref('')
const alertType = ref('success') // success, error, info
const showConfirm = ref(false)
const confirmMessage = ref('')
const confirmCallback = ref(null)

// 计算属性
const filteredKnowledge = computed(() => {
  let filtered = knowledgeList.value

  // 按分类筛选
  if (selectedTypeId.value !== null && selectedType.value) {
    filtered = filtered.filter(item => item.kno_type === selectedType.value.kno_type)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.kno_title.toLowerCase().includes(keyword) ||
      item.kno_type.toLowerCase().includes(keyword) ||
      item.kno_authid.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 方法
const loadKnowledges = async () => {
  try {
    loading.value = true
    console.log('开始获取知识文档数据...')
    const response = await getKnowledges()
    console.log('知识文档API响应:', response)
    
    if (response.code === 200) {
      knowledgeList.value = response.data || []
      console.log('知识文档数据:', knowledgeList.value)
    } else {
      console.error('获取知识文档失败:', response.message)
      alert('获取知识文档失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取知识文档失败:', error)
    alert('获取知识文档失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const onTypeSelected = (type) => {
  selectedTypeId.value = type ? type.id : null
  selectedType.value = type
}

const onSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const clearSearch = () => {
  searchKeyword.value = ''
}

// 自定义提示方法
const showCustomAlert = (message, type = 'success') => {
  alertMessage.value = message
  alertType.value = type
  showAlert.value = true
}

const showCustomConfirm = (message, callback) => {
  confirmMessage.value = message
  confirmCallback.value = callback
  showConfirm.value = true
}

const handleAlertClose = () => {
  showAlert.value = false
}

const handleConfirmYes = () => {
  if (confirmCallback.value) {
    confirmCallback.value()
  }
  showConfirm.value = false
}

const handleConfirmNo = () => {
  showConfirm.value = false
}


const handleDelete = async (knowledge) => {
  // 获取当前登录用户
  const currentUser = getUser()
  const currentUserName = currentUser?.username
  
  // 检查是否是文档作者
  if (knowledge.kno_authid !== currentUserName) {
    showCustomAlert('您只能删除自己创建的文档', 'error')
    return
  }
  
  showCustomConfirm(`确定要删除知识文档"${knowledge.kno_title}"吗？`, async () => {
    try {
      loading.value = true
      const response = await deleteKnowledge(knowledge.kno_id)
      if (response.code === 200) {
        await loadKnowledges()
        // 刷新分类统计
        if (typeNavigationRef.value) {
          await typeNavigationRef.value.refreshStats()
        }
        showCustomAlert('知识文档删除成功', 'success')
      } else {
        showCustomAlert('删除失败: ' + response.message, 'error')
      }
    } catch (error) {
      console.error('删除知识文档失败:', error)
      showCustomAlert('删除失败: ' + error.message, 'error')
    } finally {
      loading.value = false
    }
  })
}

const handleUse = (knowledge) => {
  // 打开文档预览
  previewDocument.value = knowledge
  showPreviewModal.value = true
}

// 格式化时间显示
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  try {
    const date = new Date(dateTime)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTime
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '已发布',
    2: '草稿',
    3: '待审核'
  }
  return statusMap[status] || '未知'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    1: 'published',
    2: 'draft',
    3: 'pending'
  }
  return classMap[status] || 'unknown'
}



// 上传弹窗相关方法
const openUploadModal = () => {
  showUploadModal.value = true
}

const closeUploadModal = () => {
  showUploadModal.value = false
}

const handleUploadSuccess = async (result) => {
  // 刷新知识文档列表
  await loadKnowledges()
  
  // 刷新分类统计
  if (typeNavigationRef.value) {
    await typeNavigationRef.value.refreshStats()
  }
}

// 预览弹窗相关方法
const closePreviewModal = () => {
  showPreviewModal.value = false
  previewDocument.value = null
}

// 生命周期
onMounted(() => {
  loadKnowledges()
})
</script>

<style scoped>
.knowledge-management-container {
  padding: 1rem;
  background: var(--bg-secondary);
  color: var(--text-primary);
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
}

.main-content {
  display: flex;
  gap: 1.5rem;
  align-items: flex-start;
  flex: 1;
}

.navigation-sidebar {
  flex: 0 0 300px;
  min-width: 300px;
}

.content-area {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}


.filter-section {
  background: transparent;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  display: flex;
  gap: 1rem;
  align-items: center;
  justify-content: flex-end;
  flex-shrink: 0;
}

.search-box {
  display: flex;
  align-items: center;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  overflow: hidden;
  flex: 1;
  max-width: 300px;
  min-height: 2.75rem;
}

.search-input {
  flex: 1;
  padding: 0.75rem 1.25rem;
  border: none;
  background: transparent;
  color: #374151;
  font-size: 0.875rem;
  outline: none;
}

.search-input::placeholder {
  color: #9ca3af;
}

.search-box:hover {
  border-color: #9ca3af;
}

.search-box:focus-within {
  border-color: #3b82f6;
  box-shadow: 0 0 0 1px #3b82f6;
}

.clear-btn {
  background: none;
  border: none;
  color: #9ca3af;
  font-size: 1.25rem;
  font-weight: bold;
  cursor: pointer;
  padding: 0.25rem;
  margin-right: 0.75rem;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.clear-btn:hover {
  background: #f3f4f6;
  color: #6b7280;
}

/* 表格行过渡动画 */
.table-row {
  transition: all 0.3s ease;
  animation: fadeInUp 0.4s ease-out;
}

.table-row:hover {
  background: #f8fafc;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 优化的加载状态 */
.loading-cell {
  text-align: center;
  padding: 3rem 1rem;
  background: #f8fafc;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 0.5rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 优化的空状态 */
.empty-cell {
  text-align: center;
  padding: 0;
  background: transparent;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  animation: fadeIn 0.5s ease-out;
}

.empty-icon {
  font-size: 3rem;
  opacity: 0.6;
}

.empty-content h3 {
  margin: 0;
  color: #6b7280;
  font-size: 1.125rem;
  font-weight: 500;
}

.empty-content p {
  margin: 0;
  color: #9ca3af;
  font-size: 0.875rem;
  max-width: 300px;
  line-height: 1.5;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 表格整体过渡 */
.knowledge-table {
  transition: all 0.3s ease;
}

.knowledge-table:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 按钮过渡优化 */
.btn-sm {
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
}

.btn-sm:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.btn-sm:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 自定义提示框样式 */
.custom-alert-overlay,
.custom-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.custom-alert,
.custom-confirm {
  background: white;
  border-radius: 0.75rem;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  animation: slideIn 0.3s ease-out;
  text-align: center;
}

.alert-icon,
.confirm-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  font-weight: bold;
  margin: 0 auto 1rem;
}

.alert-icon.success {
  background: #dcfce7;
  color: #16a34a;
}

.alert-icon.error {
  background: #fee2e2;
  color: #dc2626;
}

.alert-icon.info {
  background: #dbeafe;
  color: #2563eb;
}

.confirm-icon {
  background: #fef3c7;
  color: #d97706;
}

.alert-content h3,
.confirm-content h3 {
  margin: 0 0 1.5rem 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 500;
  line-height: 1.5;
}

.alert-btn {
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 0.5rem;
  padding: 0.75rem 2rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.alert-btn:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.confirm-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.confirm-btn {
  border: none;
  border-radius: 0.5rem;
  padding: 0.75rem 2rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-btn.cancel {
  background: #f3f4f6;
  color: #374151;
}

.confirm-btn.cancel:hover {
  background: #e5e7eb;
}

.confirm-btn.confirm {
  background: #dc2626;
  color: white;
}

.confirm-btn.confirm:hover {
  background: #b91c1c;
  transform: translateY(-1px);
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}


.filter-options {
  display: flex;
  gap: 1rem;
}

.filter-select {
  padding: 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 0.375rem;
  background: var(--bg-primary);
  color: var(--text-primary);
  font-size: 0.875rem;
}

.knowledge-table {
  background: var(--bg-primary);
  color: var(--text-primary);
  border-radius: 0.75rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 1.6rem;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 400px;
}

table {
  width: 100%;
  border-collapse: collapse;
  flex: 1;
  height: auto;
}

table thead {
  display: table-header-group;
}

table tbody {
  display: block;
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #cbd5e1 #f1f5f9;
}

/* 自定义滚动条样式 */
table tbody::-webkit-scrollbar {
  width: 8px;
}

table tbody::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

table tbody::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
}

table tbody::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

table thead tr,
table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}

/* 确保空状态行能够正确居中 */
table tbody tr.empty-row {
  display: table;
  width: 100%;
  table-layout: fixed;
}

table tbody tr.empty-row td {
  display: table-cell;
  width: 100%;
  text-align: center;
  vertical-align: middle;
}

th {
  background: var(--bg-tertiary);
  padding: 1rem;
  text-align: left;
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

td {
  padding: 1rem;
  border-bottom: 1px solid var(--border-color);
  color: var(--text-secondary);
}

/* 设置固定列宽并居中 */
th:first-child,
td:first-child {
  width: 60px;
  padding: 1rem 0.5rem;
  text-align: center;
}

th:nth-child(2),
td:nth-child(2) {
  width: 200px;
  padding: 1rem 0.5rem;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

th:nth-child(3),
td:nth-child(3) {
  width: 120px;
  padding: 1rem 0.5rem;
  text-align: center;
}

th:nth-child(4),
td:nth-child(4) {
  width: 100px;
  padding: 1rem 0.5rem;
  text-align: center;
}

th:nth-child(5),
td:nth-child(5) {
  width: 180px;
  padding: 1rem 0.5rem;
  text-align: center;
}

th:nth-child(6),
td:nth-child(6) {
  width: 200px;
  padding: 1rem 0.5rem;
  text-align: center;
}


.btn-sm {
  padding: 0.25rem 0.5rem;
  margin: 0 0.25rem;
  border: 1px solid var(--border-color);
  background: var(--bg-primary);
  color: var(--text-primary);
  border-radius: 0.25rem;
  cursor: pointer;
  font-size: 0.75rem;
}

.btn-sm:hover {
  background: var(--bg-tertiary);
}


/* 加载和空状态样式 */
.loading-cell {
  text-align: center;
  padding: 2rem;
  color: var(--text-secondary);
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.empty-cell {
  text-align: center;
  padding: 0;
  color: var(--text-secondary);
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: transparent;
}


.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border-color);
  border-top: 2px solid var(--accent-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.empty-icon {
  font-size: 2rem;
  opacity: 0.5;
}

.use-btn {
  background: #dcfce7;
  color: #15803d;
  border-color: #16a34a;
}

.use-btn:hover {
  background: #bbf7d0;
  color: #166534;
}

.delete-btn {
  background: #fee2e2;
  color: #dc2626;
  border-color: #fecaca;
}

.delete-btn:hover {
  background: #fecaca;
  color: #b91c1c;
}

.upload-btn {
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  padding: 0.75rem 1.25rem;
  cursor: pointer;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: none;
}

.upload-btn:hover {
  background: #f9fafb;
  border-color: #9ca3af;
  transform: none;
  box-shadow: none;
}

.upload-btn .btn-icon {
  font-size: 1rem;
}

.upload-btn .btn-text {
  font-weight: 500;
}

/* 标题和水印样式 */
.title-with-watermark {
  position: relative;
  display: inline-block;
  width: 100%;
}

.title-text {
  display: inline-block;
  position: relative;
}

.status-watermark {
  position: absolute;
  top: -8px;
  right: -8px;
  font-size: 0.625rem;
  font-weight: 500;
  padding: 0.125rem 0.375rem;
  border-radius: 0.25rem;
  opacity: 0.8;
  transform: rotate(12deg);
  transition: all 0.2s ease;
  pointer-events: none;
  z-index: 10;
  white-space: nowrap;
}

.status-watermark:hover {
  opacity: 1;
  transform: rotate(12deg) scale(1.05);
}

.status-watermark.published {
  background: linear-gradient(135deg, #dcfce7, #bbf7d0);
  color: #16a34a;
  box-shadow: 0 1px 3px rgba(22, 163, 74, 0.2);
}

.status-watermark.draft {
  background: linear-gradient(135deg, #fef3c7, #fde68a);
  color: #d97706;
  box-shadow: 0 1px 3px rgba(217, 119, 6, 0.2);
}

.status-watermark.pending {
  background: linear-gradient(135deg, #dbeafe, #bfdbfe);
  color: #2563eb;
  box-shadow: 0 1px 3px rgba(37, 99, 235, 0.2);
}

.status-watermark.unknown {
  background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
  color: #6b7280;
  box-shadow: 0 1px 3px rgba(107, 114, 128, 0.2);
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    gap: 1rem;
  }
  
  .navigation-sidebar {
    flex: none;
    min-width: auto;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .filter-options {
    flex-direction: column;
  }
}
</style>
